package cn.edu.zime.tjh.iotapp;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.google.zxing.BarcodeFormat;
import com.journeyapps.barcodescanner.BarcodeEncoder;

import org.java_websocket.WebSocket;
import org.java_websocket.handshake.ClientHandshake;
import org.java_websocket.server.WebSocketServer;

import java.lang.reflect.Field;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
import java.util.Map;

public class AdminActivity extends AppCompatActivity {

    private static final int PORT = 8080;
    private WebSocketServer server;
    private String serverAddress;
    private TextView serverStatusTextView;
    private TextView serverAddressTextView;
    private ImageView qrCodeImageView;
    private Button startServerButton;
    private Button logoutButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_admin);

        // 初始化UI组件
        serverStatusTextView = findViewById(R.id.serverStatusTextView);
        serverAddressTextView = findViewById(R.id.serverAddressTextView);
        qrCodeImageView = findViewById(R.id.qrCodeImageView);
        startServerButton = findViewById(R.id.startServerButton);
        logoutButton = findViewById(R.id.logoutButton);

        // 获取本地IP地址
        serverAddress = getLocalIpAddress();
        if (serverAddress != null) {
            serverAddressTextView.setText("服务器地址: ws://" + serverAddress + ":" + PORT);
        } else {
            serverAddressTextView.setText("无法获取服务器地址");
            startServerButton.setEnabled(false);
        }

        // 设置按钮点击事件
        startServerButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (server == null) {
                    startWebSocketServer();
                    startServerButton.setText("停止服务器");
                } else {
                    stopWebSocketServer();
                    startServerButton.setText("启动服务器");
                }
            }
        });

        logoutButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                stopWebSocketServer();
                finish();
            }
        });
    }

    private void startWebSocketServer() {
        try {
            int port = PORT;
            server = new WebSocketServer(new InetSocketAddress(port)) {
                @Override
                public void onOpen(WebSocket conn, ClientHandshake handshake) {
                    String clientAddress = conn.getRemoteSocketAddress().getAddress().getHostAddress();
                    Log.d("WebSocketServer", "新客户端连接: " + clientAddress);
                    
                    // 发送欢迎消息
                    conn.send("欢迎连接到物联网管理服务器");
                    
                    // 启动设备监控界面
                    Intent monitorIntent = new Intent(AdminActivity.this, DeviceMonitorActivity.class);
                    monitorIntent.putExtra("CLIENT_INFO", clientAddress);
                    
                    // 设置客户端WebSocket连接
                    DeviceMonitorActivity.setClientSocket(conn);
                    
                    startActivity(monitorIntent);
                }

                @Override
                public void onClose(WebSocket conn, int code, String reason, boolean remote) {
                    Log.d("WebSocketServer", "客户端连接关闭");
                }

                @Override
                public void onMessage(WebSocket conn, String message) {
                    Log.d("WebSocketServer", "收到消息: " + message);
                    
                    // 将消息转发到监控界面处理
                    try {
                        // 获取当前前台Activity
                        if (getCurrentActivity() instanceof DeviceMonitorActivity) {
                            ((DeviceMonitorActivity) getCurrentActivity()).handleClientData(message);
                        }
                    } catch (Exception e) {
                        Log.e("WebSocketServer", "处理消息错误: " + e.getMessage());
                    }
                }

                @Override
                public void onError(WebSocket conn, Exception ex) {
                    Log.e("WebSocketServer", "WebSocket错误: " + ex.getMessage());
                }

                @Override
                public void onStart() {
                    Log.d("WebSocketServer", "WebSocket服务器已启动");
                }
            };
            
            // 设置连接超时
            server.setConnectionLostTimeout(100);
            
            // 在新线程中启动服务器
            new Thread(new Runnable() {
                @Override
                public void run() {
                    server.start();
                }
            }).start();
            
            // 更新UI
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    serverStatusTextView.setText("WebSocket服务器状态: 已启动");
                    Toast.makeText(AdminActivity.this, "WebSocket服务器已启动", Toast.LENGTH_SHORT).show();
                    generateQRCode("ws://" + serverAddress + ":" + PORT);
                }
            });
            
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(this, "启动服务器失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

    private void stopWebSocketServer() {
        if (server != null) {
            try {
                server.stop();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        serverStatusTextView.setText("WebSocket服务器状态: 已停止");
                        qrCodeImageView.setImageBitmap(null);
                        Toast.makeText(AdminActivity.this, "WebSocket服务器已停止", Toast.LENGTH_SHORT).show();
                    }
                });
                server = null;  // 停止后将服务器引用设为null
            } catch (Exception e) {
                e.printStackTrace();
                Toast.makeText(this, "停止服务器失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
            }
        }
    }

    private void generateQRCode(String content) {
        try {
            BarcodeEncoder barcodeEncoder = new BarcodeEncoder();
            Bitmap bitmap = barcodeEncoder.encodeBitmap(content, BarcodeFormat.QR_CODE, 400, 400);
            qrCodeImageView.setImageBitmap(bitmap);
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(this, "生成二维码失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

    private String getLocalIpAddress() {
        try {
            for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
                NetworkInterface intf = en.nextElement();
                for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress() && !inetAddress.getHostAddress().contains(":")) {
                        return inetAddress.getHostAddress();
                    }
                }
            }
        } catch (SocketException e) {
            e.printStackTrace();
        }
        return null;
    }

    // 获取当前活动的Activity
    private Activity getCurrentActivity() {
        try {
            Class activityThreadClass = Class.forName("android.app.ActivityThread");
            Object activityThread = activityThreadClass.getMethod("currentActivityThread").invoke(null);
            Field activitiesField = activityThreadClass.getDeclaredField("mActivities");
            activitiesField.setAccessible(true);
            
            Map<Object, Object> activities = (Map<Object, Object>) activitiesField.get(activityThread);
            if (activities == null) return null;
            
            for (Object activityRecord : activities.values()) {
                Class activityRecordClass = activityRecord.getClass();
                Field pausedField = activityRecordClass.getDeclaredField("paused");
                pausedField.setAccessible(true);
                if (!pausedField.getBoolean(activityRecord)) {
                    Field activityField = activityRecordClass.getDeclaredField("activity");
                    activityField.setAccessible(true);
                    return (Activity) activityField.get(activityRecord);
                }
            }
        } catch (Exception e) {
            Log.e("ActivityUtils", "获取当前Activity失败: " + e.getMessage());
        }
        
        return null;
    }

    @Override
    protected void onDestroy() {
        stopWebSocketServer();
        super.onDestroy();
    }
} 